package com.meituan.catering.management.common.api.factory;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author mac
 */
public class MethodCacheManager {
    private static final String DOT = ".";
    private static ConcurrentHashMap<String, Method> caches = new ConcurrentHashMap();

    private MethodCacheManager() {
    }

    public static Method fetchMethod(Class<?> clazz, String methodName) {
        if (clazz != null && !StringUtils.isEmpty(methodName)) {
            String key = buildCacheKey(clazz, methodName);
            Method method = (Method) caches.get(key);
            if (method == null) {
                initCache(clazz);
            }

            method = (Method) caches.get(key);
            return method;
        } else {
            return null;
        }
    }

    private static void initCache(Class<?> clazz) {
        Method[] methods = clazz.getMethods();
        if (null != methods) {
            Method[] var2 = methods;
            int var3 = methods.length;

            for (int var4 = 0; var4 < var3; ++var4) {
                Method method = var2[var4];
                String methodName = method.getName();
                if (isNeedCache(methodName)) {
                    caches.put(buildCacheKey(clazz, methodName), method);
                }
            }

        }
    }

    private static boolean isNeedCache(String methodName) {
        return !"setData".equals(methodName) && !"setStatus".equals(methodName) ? Boolean.FALSE : Boolean.TRUE;
    }

    private static String buildCacheKey(Class<?> clazz, String methodName) {
        StringBuilder builder = new StringBuilder(32);
        builder.append(clazz.getName()).append(".").append(methodName);
        return builder.toString();
    }
}
